package com.tofine.smarthome.adapter;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.SwitchCompat;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.daimajia.swipe.SwipeLayout;
import com.daimajia.swipe.adapters.RecyclerSwipeAdapter;
import com.squareup.picasso.Picasso;
import com.tofine.smarthome.R;
import com.tofine.smarthome.model.Device;
import com.tofine.smarthome.rest.RestClient;
import com.tofine.smarthome.rest.model.Command;
import com.tofine.smarthome.ui.DeviceInfoActivity;
import com.tofine.smarthome.util.CommandUtils;

import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * @author ddMax
 * @since 2016/4/29 0:59.
 */
public class FavoriteRecyclerViewAdapter extends RecyclerSwipeAdapter<FavoriteRecyclerViewAdapter.ViewHolder> {

    public static class ViewHolder extends RecyclerView.ViewHolder {
        @Bind(R.id.swipe) SwipeLayout swipeLayout;
        @Bind(R.id.favorite) ImageView favoriteView;
        @Bind(R.id.device_item) RelativeLayout mItem;
        @Bind(R.id.device_image) ImageView mDeviceImage;
        @Bind(R.id.device_title) TextView mDeviceTitle;
        @Bind(R.id.device_switch) SwitchCompat mDeviceSwitch;

        public ViewHolder(View itemView) {
            super(itemView);
            ButterKnife.bind(this, itemView);
        }
    }

    private Context mContext;
    private List<Device> mDataSet;

    public FavoriteRecyclerViewAdapter(Context context, List<Device> dataSet) {
        this.mContext = context;
        this.mDataSet = dataSet;
    }

    /**
     * 创建ViewHolder
     * @param parent 对应的父视图
     * @param viewType 一个标志，我们根据该标志可以实现渲染不同类型的ViewHolder
     * @return ViewHolder对象
     */
    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(mContext).inflate(R.layout.item_favorite, parent, false);
        return new ViewHolder(view);
    }

    /**
     * 绑定每个ViewHolder的数据
     * @param holder 当前的ViewHolder实例
     * @param position ViewHolder实例的位置
     */
    @Override
    public void onBindViewHolder(final ViewHolder holder, final int position) {
        final Device device = mDataSet.get(position);
        // 整个Item点击监听
        holder.mItem.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(mContext, DeviceInfoActivity.class);
                Bundle bundle = new Bundle();
                bundle.putSerializable("device", device);
                bundle.putInt("mode", DeviceInfoActivity.MODE_EDIT);
                intent.putExtras(bundle);
                mContext.startActivity(intent);
            }
        });
        // 设备图片
        Picasso.with(mContext).load(Uri.parse(device.image)).into(holder.mDeviceImage);
        // 设备名称
        holder.mDeviceTitle.setText(device.name);
        // 设备开关状态
        holder.mDeviceSwitch.setChecked(device.status);
        holder.mDeviceSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, final boolean isChecked) {
                device.status = isChecked;

                final ProgressDialog dialog = new ProgressDialog(mContext);
                dialog.setMessage("正在与设备通信");
                dialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
                dialog.show();
                RestClient.getInstance().getApiService().sendCommand(device._id, CommandUtils.genCommand(device)).enqueue(new Callback<Command>() {
                    @Override
                    public void onResponse(Call<Command> call, Response<Command> response) {
                        dialog.cancel();
                        device.save();
                    }

                    @Override
                    public void onFailure(Call<Command> call, Throwable t) {

                        dialog.cancel();
                        device.save();
                        t.printStackTrace();
                    }
                });

            }
        });
        // 是否标记为收藏
        if (device.isFavorite) {
            setFavoriteIcon(holder, true);
            holder.favoriteView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    // 点击收藏
                    device.isFavorite = false;

                    RestClient.getInstance().getApiService().updateDevice(device._id, device).enqueue(new Callback<Device>() {
                        @Override
                        public void onResponse(Call<Device> call, Response<Device> response) {
                            device.save();
                            setFavoriteIcon(holder, true);
                            holder.swipeLayout.close(true);
                            // 删除该项
                            mItemManger.removeShownLayouts(holder.swipeLayout);
                            mDataSet.remove(position);
                            notifyItemRemoved(position);
                            notifyItemRangeChanged(position, mDataSet.size());
                            mItemManger.closeAllItems();
                        }

                        @Override
                        public void onFailure(Call<Device> call, Throwable t) {
                            device.save();
                            setFavoriteIcon(holder, true);
                            holder.swipeLayout.close(true);
                            // 删除该项
                            mItemManger.removeShownLayouts(holder.swipeLayout);
                            mDataSet.remove(position);
                            notifyItemRemoved(position);
                            notifyItemRangeChanged(position, mDataSet.size());
                            mItemManger.closeAllItems();
                            t.printStackTrace();
                        }
                    });

                }
            });
        }
    }

    private void setFavoriteIcon(final ViewHolder holder, boolean isFavorite) {
        holder.favoriteView.setImageDrawable(ContextCompat.getDrawable(
                mContext, isFavorite ?
                R.drawable.ic_favorite_white_24dp : R.drawable.ic_favorite_border_white_24dp
        ));
    }

    /**
     * Adapter中Item总数
     * @return Item总数
     */
    @Override
    public int getItemCount() {
        return mDataSet.size();
    }

    @Override
    public int getSwipeLayoutResourceId(int position) {
        return R.id.swipe;
    }

}
